package com.px.auth.security;

import com.px.common.core.RespCode;
import com.px.common.core.RespException;
import com.px.common.util.JsonUtil;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.Map;

import static com.px.common.security.AuthConst.REDIS_TOKEN_EXPIRE;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public UserDetails authenticateToken(@NonNull String token) {
        Jwt jwt = JwtHelper.decode(token);
        Map claims = JsonUtil.fromJson(jwt.getClaims(), Map.class);
        String userid = (String) claims.get("userid");
        Long iat = Long.valueOf((String) claims.get("iat"));
        Double preIat = redisTemplate.opsForZSet().score(REDIS_TOKEN_EXPIRE, userid);
        if (preIat != null && iat < preIat)
            throw new RespException(RespCode.TOKEN_ERROR, token);
        return User.builder()
                .username(userid)
                .password("")
                .authorities(AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("roles")))
                .build();
    }
}
